package com.quanquan.store.dao;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

@Repository
public class CouponCacheDao {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String PREFIX = "couponNum-";

    /**
     * 获取缓存中的优惠券数量
     *
     * @param id
     * @return
     */
    public String get(@NotNull String id) {
        if (stringRedisTemplate.hasKey(PREFIX.concat(id))) {
            return stringRedisTemplate.opsForValue().get(PREFIX.concat(id));
        } else {
            return null;
        }
    }

    /**
     * 向缓存中券数量
     *
     * @param id
     * @return
     */
    public String save(@NotNull String id, String remainTotal) {
        if (id == null) {
            return null;
        } else {
            // 设置订单5分钟过期
            stringRedisTemplate.opsForValue().set(PREFIX.concat(id), remainTotal);
            return remainTotal;
        }
    }

    /**
     * 删除缓存
     *
     * @param orderNum
     * @return
     */
    public boolean delete(@NotNull String orderNum) {
        if (stringRedisTemplate.hasKey(PREFIX.concat(orderNum))) {
            stringRedisTemplate.delete(PREFIX.concat(orderNum));
            return true;
        } else {
            return false;
        }
    }
}
